package com.pansoft.openplanet.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.chat.activity.LuckMoneyHistoryActivity;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.model.Group;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.widget.SecretPassInputDialog;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.efounder.utils.CommonDecimalFormat;
import com.efounder.utils.ResStringUtil;
import com.google.gson.Gson;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.bean.EscrowAccountListBean;
import com.pansoft.openplanet.constant.IPAssetsConstant;
import com.pansoft.openplanet.fragment.RedPackagePrepareDialogFragment;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.utilcode.util.LogUtils;
import com.utilcode.util.ReflectUtils;
import com.utilcode.util.ToastUtils;

import net.sf.json.JSONObject;

import java.math.BigDecimal;
import java.util.HashMap;

import static com.efounder.chat.item.RedPackageItem.PACKAGE_NO_OPEN;

/**
 * 发送红包填写信息界面
 *
 * @author yqs
 */

public class LuckMoneyPrepareActivity extends TCBaseActivity implements View.OnClickListener {


    private final String TAG = "LuckMoneyPrepareActivity";
    private TextView tvTitle;
    //输入的金额
    private EditText etMoney;
    //留言
    private EditText etLeaveMessage;
    private TextView tvMoney;
    private Button butSend;

    private TextView tvFirstTitle;
    private RelativeLayout rlGroupRpLayput;
    private TextView tvTips1;
    private TextView tvTips2;
    //红包个数
    private EditText etCount;
    private TextView tvTips3;
    private TextView tvUnit;

    private LinearLayout llWalletLayout;
    private TextView tvWallet;
    private TextView tvWalletAdddress;
    private LinearLayout llAssetsLayout;
    private TextView tvHbdb;//红包代币 txtview
    private TextView tvAssetname;
    private ImageView ivArrow;
    private TextView tvTuoguanBalance;//托管余额
    private TextView tvTuoguanUnit;
    private TextView tvTuoguanOperation;
    private SmartRefreshLayout refreshLayout;
    private TextView tvTextPin;
    private TextView tvRecord;


    private int toUserId;
    private byte chatType;
    private StubObject mStubObject;
    private CommonDecimalFormat decimalFormat = new CommonDecimalFormat("0.00000");//构造方法的字符格式这里如果小数不足2位,
    private boolean isLuckMode = true;//拼手气红包
    private boolean isGroup = false;//是否是群组
    //红包的单位 默认 PWR 能量币
    private String unit = "PWR";
    private int chainId = IPAssetsConstant.CHAIN_ID_TURBOCHAIN;
    //默认红包个数0
    private int redPackageCount = 1;

    //代币信息
    EscrowAccountListBean.AssetsBean assetsBean;


    public static void start(Context context) {
        Intent starter = new Intent(context, LuckMoneyPrepareActivity.class);
        // starter.putExtra();
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.assets_activity_luck_money_prepare);
        initView();
        initListener();
        initData();
    }


    private void initView() {
        //标题
        tvTitle = (TextView) this.findViewById(R.id.tv_title);
        etMoney = (EditText) findViewById(R.id.et_money);
        etLeaveMessage = (EditText) findViewById(R.id.et_leave_message);
        tvMoney = (TextView) findViewById(R.id.tv_money);
        butSend = (Button) findViewById(R.id.but_send);
        butSend.setOnClickListener(this);
        tvFirstTitle = (TextView) findViewById(R.id.tv_first_title);
        rlGroupRpLayput = (RelativeLayout) findViewById(R.id.rl_group_rp_layput);
        tvTips1 = (TextView) findViewById(R.id.tv_tips1);
        tvTips2 = (TextView) findViewById(R.id.tv_tips2);
        etCount = (EditText) findViewById(R.id.et_count);
        tvTips3 = (TextView) findViewById(R.id.tv_tips3);
        tvUnit = (TextView) findViewById(R.id.tv_unit);

        tvTuoguanBalance = (TextView) findViewById(R.id.tv_tuoguan_balance);
        tvTuoguanUnit = (TextView) findViewById(R.id.tv_tuoguan_unit);
        tvTuoguanOperation = (TextView) findViewById(R.id.tv_tuoguan_operation);
        llWalletLayout = (LinearLayout) findViewById(R.id.ll_wallet_layout);
        llWalletLayout.setVisibility(View.GONE);
        llWalletLayout.setOnClickListener(this);
        tvWallet = (TextView) findViewById(R.id.tv_wallet);
        tvWalletAdddress = (TextView) findViewById(R.id.tv_wallet_adddress);
        llAssetsLayout = (LinearLayout) findViewById(R.id.ll_assets_layout);
        //llAssetsLayout.setVisibility(View.GONE);
        tvHbdb = (TextView) findViewById(R.id.tv_hbdb);
        tvAssetname = (TextView) findViewById(R.id.tv_assetname);
        ivArrow = (ImageView) findViewById(R.id.ivArrow);
        refreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
        llAssetsLayout.setOnClickListener(this);
        tvTuoguanOperation.setOnClickListener(this);
        tvTextPin = (TextView) findViewById(R.id.tv_text_pin);
        GradientDrawable myGrad = (GradientDrawable) tvTextPin.getBackground();
        myGrad.setColor(getResources().getColor(R.color.op_blue_color));
        tvRecord = (TextView) findViewById(R.id.tv_save);
        tvRecord.setVisibility(View.VISIBLE);
        tvRecord.setOnClickListener(this);

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //  EFHttpRequest.cancelRequest(TAG);
        try {
            ReflectUtils reflectUtils = ReflectUtils.reflect(EnvironmentVariable.getProperty("shareClass", ""));
            reflectUtils.newInstance().method("release", this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initData() {
        tvTitle.setText(ResStringUtil.getString(R.string.open_planet_send_red_packet));
        //tvTitle.setText(ResStringUtil.getString(R.string.wrchatview_red_detail));
        tvRecord.setText(ResStringUtil.getString(R.string.open_planet_red_packet_record));
        mStubObject = (StubObject) getIntent().getSerializableExtra("stubObject");
        if (mStubObject == null) {
            //应用外红包分享
            initAppExternalShare();
        } else {
            //应用内聊天红包
            toUserId = Integer.parseInt(mStubObject.getString("toUserId", "0"));
            chatType = Byte.parseByte(mStubObject.getString("chatType", ""));
            tvMoney.setText(getResources().getString(R.string.im_red_package_money_unit1, "0.00"));
            if (chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
                initPersonalData();
            } else {
                isGroup = true;
                initGroupRedPackageData();
            }
        }


        requestAssetData();

    }


    private void initAppExternalShare() {
        tvTips3.setVisibility(View.GONE);
        llWalletLayout.setVisibility(View.GONE);
        llAssetsLayout.setVisibility(View.VISIBLE);
        tvMoney.setText(getResources().getString(R.string.im_total_money, "0.000000", "PWR"));
        updateShowText(true);
    }

    private void initGroupRedPackageData() {
        rlGroupRpLayput.setVisibility(View.VISIBLE);
        updateShowText(true);

        Group group = WeChatDBManager.getInstance().getGroupInGroups(toUserId, true);
        if (group != null && group.getUsers() != null) {
            tvTips3.setText(getResources().getString(R.string.im_money_prepare_tip_3, group.getUsers().size() + ""));
        } else {
            tvTips3.setText(getResources().getString(R.string.im_money_prepare_tip_3, "0"));
        }
    }

    private void updateShowText(boolean isLuckMode) {
        if (isLuckMode) {
            tvFirstTitle.setText(R.string.open_planet_total_coin_number);
            tvTips1.setText(R.string.im_money_prepare_tip_1_1);
            tvTips2.setText(R.string.im_money_prepare_tip_2_1);
            tvTextPin.setVisibility(View.VISIBLE);
        } else {
            tvFirstTitle.setText(R.string.open_planet_single_coin_number);
            tvTips1.setText(R.string.im_money_prepare_tip_1_2);
            tvTips2.setText(R.string.im_money_prepare_tip_2_2);
            tvTextPin.setVisibility(View.GONE);

        }
        setTotalMoney();
    }


    private void initPersonalData() {
        rlGroupRpLayput.setVisibility(View.GONE);
        tvTextPin.setVisibility(View.GONE);
        //单人红包没有拼手气
        isLuckMode = false;
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.but_send) {
            //点击发送
            showVerifyPwdDialog();
        } else if (id == R.id.ll_assets_layout) {
            //选择红包代币
            EscrowAccountActivity.start(LuckMoneyPrepareActivity.this, true);
        } else if (id == R.id.tv_tuoguan_operation) {
            //点击转入
            if (assetsBean == null) {
                ToastUtil.showToast(AppContext.getInstance(), R.string.open_planet_package_app_error);
                return;
            }
            EscrowRechargeActivity.start(LuckMoneyPrepareActivity.this, assetsBean);
        } else if (id == R.id.tv_save) {
            //点击进入红包记录
            LuckMoneyHistoryActivity.start(LuckMoneyPrepareActivity.this);
        }
    }


    private void initListener() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                requestAssetData();
            }
        });
        etMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String temp = s.toString();
                if (s.length() == 0) {
                    butSend.setEnabled(false);
                    butSend.setClickable(false);
//                    tvMoney.setText(getResources().getString(R.string.im_red_package_money_unit1, "0.00"));
                    tvMoney.setText(getResources().getString(R.string.im_total_money, "0.00000", unit));
                    return;
                } else {
                    butSend.setEnabled(true);
                    butSend.setClickable(true);
                }
                int posDot = temp.indexOf(".");
                if (posDot == 0) {
//                    String text = temp.toString() + "0.00000";
//                    tvMoney.setText(getResources().getString(R.string.im_total_money, text, unit));
//                    if (!isLuckMode) {
//                        setTotalMoney();
//                    }
                    etMoney.setText("0.");
                    etMoney.setSelection(etMoney.getText().length());
                    return;
                }
                if (posDot < 0) {
                    String text = temp.toString() + ".00000";
                    tvMoney.setText(getResources().getString(R.string.im_total_money, text, unit));

                    if (!isLuckMode) {
                        setTotalMoney();
                    }
                    return;
                }
                if (temp.length() - posDot - 1 == 0) {
                    String text = temp.toString() + "00000";
                    tvMoney.setText(getResources().getString(R.string.im_total_money, text, unit));
                    if (!isLuckMode) {
                        setTotalMoney();
                    }
                    return;
                }
                if (temp.length() - posDot - 1 > 5) {
                    s.delete(posDot + 6, posDot + 7);
                }
                //  String text = String.format("%.2f", temp);
                String text = null;
                try {
                    double money = Double.valueOf(temp.toString());
                    text = decimalFormat.format(money);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                tvMoney.setText(getResources().getString(R.string.im_total_money, text, unit));
                if (!isLuckMode) {
                    setTotalMoney();
                }
            }
        });
        //红包数量
        etCount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (s.length() > 0) {
                    if (s.toString().equals("0")) {
                        ToastUtils.showShort(R.string.open_planet_red_packet_number_not_zero);
                        etCount.setText("1");
                        return;
                    }
                    redPackageCount = Integer.valueOf(s.toString());
                    if (isLuckMode == true) {
                        return;
                    }
                    try {
                        double oneMoney = Double.parseDouble(etMoney.getText().toString());
                        String text = decimalFormat.format(oneMoney * redPackageCount);
                        tvMoney.setText(getResources().getString(R.string.im_total_money, text, unit));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }
            }
        });
        tvTips2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isLuckMode = !isLuckMode;
                updateShowText(isLuckMode);
            }
        });
    }

    //etditext 变化设置总金额
    private void setTotalMoney() {
        if (etCount.getText().length() > 0) {
            try {
                double oneMoney = Double.parseDouble(etMoney.getText().toString());
                String text = decimalFormat.format(oneMoney * redPackageCount);
                if (isLuckMode) {
                    text = decimalFormat.format(oneMoney * 1);
                }
                tvMoney.setText(getResources().getString(R.string.im_total_money, text, unit));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                assetsBean = (EscrowAccountListBean.AssetsBean) data.getSerializableExtra("assetBean");
                refreshBalanceAndUnit();
            }
        }
    }

    private void refreshBalanceAndUnit() {
        unit = assetsBean.getCoinName();
        tvUnit.setText(unit);
        tvTuoguanUnit.setText(unit);
        tvTuoguanBalance.setText(decimalFormat.format(assetsBean.getAvailableCoin()) + "");
        tvAssetname.setText(unit);
        if (etMoney.getText().length() > 0) {
//            tvMoney.setText(getResources().getString(R.string.im_total_money, etMoney.getText().toString(), unit));
            setTotalMoney();
        } else {
            tvMoney.setText(getResources().getString(R.string.im_total_money, "0.00000", unit));

        }
    }

    private void showVerifyPwdDialog() {
        try {
            Double.valueOf(etMoney.getText().toString());
        } catch (NumberFormatException e) {
            e.printStackTrace();
            ToastUtils.showShort(R.string.open_planet_red_packet_amount_illegal);
            return;
        }
        if (isGroup || mStubObject == null) {
            if (etCount.getText().length() == 0) {
                ToastUtils.showShort(R.string.open_planet_input_red_packet_number);
                return;
            }
            if ("0".equals(etCount.getText().toString())) {
                ToastUtils.showShort(R.string.open_planet_red_packet_number_not_zero);
                return;
            }
        }
        double totalMoney = 0d;
        try {

            double tuobuanMoney = Double.valueOf(tvTuoguanBalance.getText().toString());
            double oneMoney = Double.parseDouble(etMoney.getText().toString());
            String text = decimalFormat.format(oneMoney * redPackageCount);
            if (isLuckMode) {
                text = decimalFormat.format(oneMoney * 1);
            }
            totalMoney = Double.valueOf(text);
            if (totalMoney > tuobuanMoney) {
                ToastUtils.showShort(R.string.open_planet_escrow_balance_shorted);
                return;
            }
            //单个红包金额必须》0.00001
            if (div(text, String.valueOf(redPackageCount), 8) < 0.00001) {
                ToastUtils.showShort(R.string.open_planet_single_red_packet_amount);
                return;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        final double finalTotalMoney = totalMoney;
        //保留五位小数
        BigDecimal bigDecimal = new BigDecimal(finalTotalMoney + "").setScale(5, BigDecimal.ROUND_HALF_UP);
        final String total = bigDecimal.toString();

        SecretPassInputDialog dialog = new SecretPassInputDialog(this, new SecretPassInputDialog.OnEnterClick() {
            @Override
            public void passVerifySuccess(String passWord) {
                //密码正确，开始准备红包
                createRedPackage(total);
            }
        });
        dialog.getTips().setVisibility(View.GONE);
        dialog.show();
    }

    public static double div(String totalMoney, String count, int scale) {

        BigDecimal b1 = new BigDecimal(totalMoney);
        BigDecimal b2 = new BigDecimal(count);
        return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    //请求代币信息
    private void requestAssetData() {

        final HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());

        TCRequestUtil.getCommonRequest(TAG, "trusteeship/assets", map, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                refreshLayout.finishRefresh(100);
                try {
                    EscrowAccountListBean escrowAccountListBean = new Gson().fromJson(response, EscrowAccountListBean.class);
                    if (escrowAccountListBean == null) {
                        return;
                    }
                    if ("success".equals(escrowAccountListBean.getResult())) {
                        if (assetsBean != null) {
                            for (int i = 0; i < escrowAccountListBean.getAssets().size(); i++) {
                                if (assetsBean.getCoinName().equals(escrowAccountListBean.getAssets().get(i).getCoinName())) {
                                    assetsBean = escrowAccountListBean.getAssets().get(i);
                                    refreshBalanceAndUnit();
                                    break;
                                }
                            }
                        } else {
//                            if (escrowAccountListBean.getAssets().size() == 0) {
//                                return;
//                            }
                            assetsBean = escrowAccountListBean.getAssets().get(0);
                            refreshBalanceAndUnit();
                        }

                    } else {

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    refreshLayout.finishRefresh(100);

                    ToastUtils.showShort(R.string.open_planet_request_escrow_balance_fail);
                }
            }

            @Override
            public void onFail(String error) {
                refreshLayout.finishRefresh(100);

                ToastUtils.showShort(R.string.open_planet_request_escrow_balance_fail);

            }
        });
    }

    //创建的红包
    private void createRedPackage(final String totalMoney) {
        HashMap<String, String> map = new HashMap<>();
//        userId 手机号
//        trusteeshipCoinId 红包币ID
//        type 类型 0 随机 1平均
//        totalMoney 总金额
//        totalSize 总共多少个
//        singleMoney 单个多少
//        remarks 备注
        //随机机红包不需要传 singleMoney
        //getPacketUser  手机号 单聊发红包必须穿这个参数


        map.put("userId", EnvironmentVariable.getUserName());
        map.put("trusteeshipCoinId", assetsBean.getTrusteeshipId() + "");
        map.put("type", isLuckMode ? "0" : "1");
        map.put("totalMoney", totalMoney);
        map.put("totalSize", redPackageCount + "");
        map.put("coinName", assetsBean.getCoinName());
        if (!isLuckMode) {
            map.put("singleMoney", etMoney.getText().toString());

        }
        //单聊发红包 只允许这个人领取
        if (mStubObject != null && chatType == StructFactory.TO_USER_TYPE_PERSONAL) {
            User user = WeChatDBManager.getInstance().getOneUserById(toUserId);
            if (!user.isExist()) {
                ToastUtils.showShort(R.string.common_text_request_user_info_fail);
                return;
            }
            map.put("getPacketUser", user.getName() + "");

        }
        final String remark = etLeaveMessage.getText().toString().equals("") ? getString(R.string.lucky_money_hint) : etLeaveMessage.getText().toString();
        map.put("remarks", remark);

        showLoading(ResStringUtil.getString(R.string.open_planet_preparing_red_packet));
        TCRequestUtil.getCommonRequest(TAG, "redpacket/createRedPacket", map, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                dismissLoading();
                LogUtils.d(response);
                try {
                    //   {"result":"success","data":"1"}
                    // {"result":"success",
                    // "data":{"endTime":1534325070362,"packetId":"c97c5753-3378-4ac5-9480-1627f8b864d8","remainMoney":0.0,"remainSize":0,"remarks":"恭喜发财，大吉大利","startTime":1534238670362,"status":1,"totalMoney":0.01,"totalSize":2,"trusteeshipCoinId":1,"type":0,"userId":"18363825829"},"url":"http://tc.solarsource.cn:9692/tcserver/redPackage/index.html?packetId=c97c5753-3378-4ac5-9480-1627f8b864d8&userId=18363825829&coinName=PWR"}
                    JSONObject jsonObject = JSONObject.fromObject(response);
                    if ("success".equals(jsonObject.optString("result"))) {
                        //ToastUtil.showToast(AppContext.getInstance(), "发送成功");
                        String url = jsonObject.optString("url", "");
                        gotoPrepared(url, remark, totalMoney, jsonObject);
                    } else {
                        ToastUtils.showShort(R.string.common_text_send_fail);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    ToastUtils.showShort(R.string.common_text_http_request_fail);
                }
            }

            @Override
            public void onFail(String error) {
                refreshLayout.finishRefresh(100);
                dismissLoading();
                ToastUtils.showShort(R.string.common_text_http_request_fail);
            }
        });

    }

    /**
     * 跳转准备好界面
     *
     * @param url        分享的url
     * @param remark     留言
     * @param totalMoney 总金额
     * @param jsonObject 服务器结果
     */
    private void gotoPrepared(final String url, final String remark, String totalMoney, JSONObject jsonObject) {
        int type = 0;
        if (mStubObject == null) {
            //web红包
            type = RedPackagePrepareDialogFragment.TYPE_WEB;
            RedPackagePrepareDialogFragment fragment = RedPackagePrepareDialogFragment.newInstance(remark, url, redPackageCount, totalMoney, unit, type);
            fragment.setCancelable(false);
            fragment.show(getSupportFragmentManager(), TAG);
        } else {
            //聊天红包，组织消息
            IMStruct002 imStruct = prepareSendMessage(totalMoney, jsonObject);
            //发送
            LogUtils.i(imStruct.toString());
            JFMessageManager.getInstance().sendMessage(imStruct);
            finish();
        }
    }

    /**
     * 组织聊天红包消息
     *
     * @param totalMoney
     * @param responseJsonObject
     * @return
     */
    private IMStruct002 prepareSendMessage(String totalMoney, JSONObject responseJsonObject) {
        // {"result":"success","data":{"endTime":1534467558590,"packetId":"0dc05094-59c5-45cd-934a-29bcc434897f","remainMoney":0.0,"remainSize":0,"remarks":"红包呗","startTime":1534381158590,"status":1,"totalMoney":0.01,"totalSize":1,"trusteeshipCoinId":1,"type":0,"userId":"18363825829"},"url":"http://tc.solarsource.cn:9692/tcserver/redPackage/index.html?packetId=0dc05094-59c5-45cd-934a-29bcc434897f&userId=18363825829&coinName=PWR&trusteeshipCoinId=1&remarks=红包呗"}
        //组织数据
        JSONObject jsonObject = new JSONObject();
        //红包个数
        int count = etCount.getText().length() == 0 ? 1 : Integer.valueOf(etCount.getText().toString());
        //红包金额
        //留言
        String leaveMessage = etLeaveMessage.getText().length() == 0 ? getString(R.string.lucky_money_hint) : etLeaveMessage.getText().toString();
        //是否是幸运红包 （群组中）
        boolean isLuckType = false;
        if (isGroup) {
            isLuckType = isLuckMode;
        }
        //红包状态 int
        jsonObject.put("packageState", PACKAGE_NO_OPEN);
        //红包个数 int
        jsonObject.put("count", count);
        //红包总金额 字符串
        jsonObject.put("totalMoney", totalMoney);
        //留言 string
        jsonObject.put("leaveMessage", leaveMessage);
        //是否是幸运红包 1  0 int
        jsonObject.put("luckMode", isLuckType ? 0 : 1);
        //代币单位 PWR string
        jsonObject.put("assetUnit", unit);
        //红包 id String
        jsonObject.put("packetId", responseJsonObject.getJSONObject("data").optString("packetId"));
        //coin id  int
        jsonObject.put("trusteeshipCoinId", responseJsonObject.getJSONObject("data").optInt("trusteeshipCoinId"));
        //手机号  int
        jsonObject.put("phoneId", responseJsonObject.getJSONObject("data").optInt("userId"));
        jsonObject.put("data", responseJsonObject.toString());

        String message = jsonObject.toString();
        LogUtils.i(message);

        IMStruct002 imStruct002 = StructFactory.getInstance().createRedPackageMessage(message, toUserId, chatType);
        return imStruct002;
    }
}
